<?php

/**
 * Description of form
 *
 * @author ngo
 */
require_once('../../model/Form.php');

class Form_Newsletter extends Form {

    const CSS_INPUT_CLASS = 'form-text';
    const CSS_INPUT_CLASS_ERROR = 'form-text-error';
    
    private $_contexte;

    private $_civil;
    private $_firstname;
    private $_lastname;
    private $_country;
    private $_city;
    private $_email;
    private $_isValid;
    private $_errors = array();

    public function __construct($contexte) {
        
        $this->_contexte = $contexte;
        if(empty($_POST)) return;
            
        if (array_key_exists('civil', $_POST))
            $this->_civil = $_POST['civil'];
        if (array_key_exists('firstname', $_POST))
            $this->_firstname = $_POST['firstname'];
        if (array_key_exists('lastname', $_POST))
            $this->_lastname = $_POST['lastname'];
        if (array_key_exists('country', $_POST))
            $this->_country = $_POST['country'];
        if (array_key_exists('city', $_POST))
            $this->_city = $_POST['city'];
        if (array_key_exists('email', $_POST))
            $this->_email = $_POST['email'];

        $this->validateForm();

        if ($this->isValid())
            $this->_save();
    }

    public function getContexte(){
        return $this->_contexte;
    }
    
    public function getValue($field) {
        $field = '_' . $field;
        return $this->$field;
    }

    public function getClass($field) {
        if (array_key_exists($field, $this->_errors))
            return Form_Newsletter::CSS_INPUT_CLASS_ERROR;

        return Form_Newsletter::CSS_INPUT_CLASS;
    }

    public function validateForm() {
        if (!$this->isValidEmail($this->_email))
            $this->_errors['email'] = true;

        if (empty($this->_firstname))
            $this->_errors['firstname'] = true;
        if (empty($this->_lastname))
            $this->_errors['lastname'] = true;
        if (empty($this->_email))
            $this->_errors['email'] = true;

        $this->_isValid = empty($this->_errors);
    }

    public function isValid() {
        return $this->_isValid;
    }

    public function isPost() {
        return !empty($_POST);
    }
    
    private function _save() {
        require_once('../../model/Db/Newsletter.php');
        $db = new Db_Newsletter();
        $data = array();

        if (!empty($this->_civil))
            $data['civil'] = $this->_civil;
        if (!empty($this->_firstname))
            $data['firstname'] = $this->_firstname;
        if (!empty($this->_lastname))
            $data['lastname'] = $this->_lastname;
        if (!empty($this->_country))
            $data['country'] = $this->_country;
        if (!empty($this->_city))
            $data['city'] = $this->_city;
        if (!empty($this->_email))
            $data['email'] = $this->_email;

        $db->insert($data,$this->_contexte);
    }

}